package org.test.once.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.test.once.model.Module;
import org.test.once.utils.DBHelper;

/**
 * 
 * @author cennanfang
 * @date 2013-7-25
 * @fileName RoleModuleDao.java
 */
public class RoleModuleDao {
	
	private static RoleModuleDao instance;
	
	private RoleModuleDao() {}
	
	public static RoleModuleDao getInstance() {
		if(instance == null) {
			instance = new RoleModuleDao();
		}
		return instance;
	}
	
	public List<Module> searchModulesByRoleId(int roleId) throws SQLException {
		ArrayList<Module> modules = new ArrayList<Module>();
		
		String sql = "select * from t_role_module where role_id = ?";
		
		Connection conn = DBHelper.getConnection();
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, roleId);
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			int id =  rs.getInt("module_id");
			Module module = ModuleDao.getInstance().findModuleById(id);
			modules.add(module);
		}
		DBHelper.close(rs);
		DBHelper.close(pstmt);
		DBHelper.close(conn);
		
		return modules;
	}
	public void addModuleRole(int mid,int rid) throws SQLException {
		ArrayList<Module> modules = new ArrayList<Module>();
		
		String sql = "insert into t_role_module values (null,?,?)";
		
		Connection conn = DBHelper.getConnection();
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, mid);
		pstmt.setInt(1, rid);
	     pstmt.executeUpdate();
		
		
		DBHelper.close(pstmt);
		DBHelper.close(conn);
		
	
	}
}
